import { useState, useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { Table, Button, Space, Tag, Modal, message, Input, Card, Tooltip, Image, Rate, Tabs } from 'antd'
import { EyeOutlined, CheckOutlined, CloseOutlined, DownloadOutlined } from '@ant-design/icons'
import { fetchPendingReviews, reviewBookReview } from '@/store/slices/auditSlice'
import './index.scss'

const { TextArea } = Input

const ReviewManagement = () => {
  const dispatch = useDispatch()
  const { reviewList, loading } = useSelector((state) => state.audit)
  
  const [selectedRowKeys, setSelectedRowKeys] = useState([])
  const [detailVisible, setDetailVisible] = useState(false)
  const [currentReview, setCurrentReview] = useState(null)
  const [rejectVisible, setRejectVisible] = useState(false)
  const [rejectReason, setRejectReason] = useState('')
  const [activeTab, setActiveTab] = useState('all')
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)

  // 加载书评列表
  useEffect(() => {
    dispatch(fetchPendingReviews({ page, size: pageSize }))
  }, [dispatch, page, pageSize])

  // 模拟数据（作为后备）
  const [dataSource, setDataSource] = useState([
    {
      id: 1,
      bookName: '活着',
      bookCover: 'https://images.unsplash.com/photo-1544947950-fa07a98d237f?w=100',
      userName: '张三',
      rating: 5,
      title: '一部震撼人心的生命史诗',
      content: '《活着》是余华最具代表性的作品之一，通过福贵的一生展现了中国近代历史的变迁...',
      fullContent: '《活着》是余华最具代表性的作品之一，通过福贵的一生展现了中国近代历史的变迁。这本书让我深刻理解了生命的意义和价值，即使在最艰难的时刻，人也要保持对生活的热爱。余华用朴实无华的语言，讲述了一个普通人的不平凡经历，每一次苦难都让人心痛，但福贵始终没有放弃活下去的希望。这种对生命的执着和坚韧，深深地打动了我。',
      status: 'pending',
      createTime: '2024-01-20 10:30:00',
      likes: 128,
      comments: 34,
      helpful: 95,
    },
    {
      id: 2,
      bookName: '百年孤独',
      bookCover: 'https://images.unsplash.com/photo-1512820790803-83ca734da794?w=100',
      userName: '李四',
      rating: 4,
      title: '魔幻现实主义的巅峰之作',
      content: '马尔克斯的《百年孤独》是拉美文学的里程碑，布恩迪亚家族七代人的故事充满了魔幻色彩...',
      fullContent: '马尔克斯的《百年孤独》是拉美文学的里程碑，布恩迪亚家族七代人的故事充满了魔幻色彩。作者用独特的叙事手法，将现实与幻想完美融合，创造了一个既真实又虚幻的马孔多小镇。孤独是贯穿全书的主题，每个人物都在寻找着什么，却又失去着什么。这本书需要耐心品读，每一次重读都会有新的感悟。',
      status: 'approved',
      createTime: '2024-01-19 15:20:00',
      likes: 256,
      comments: 67,
      helpful: 198,
    },
    {
      id: 3,
      bookName: '三体',
      bookCover: 'https://images.unsplash.com/photo-1589998059171-988d887df646?w=100',
      userName: '王五',
      rating: 5,
      title: '中国科幻的巅峰之作',
      content: '刘慈欣的《三体》三部曲构建了一个宏大的宇宙观，黑暗森林法则令人震撼...',
      fullContent: '刘慈欣的《三体》三部曲构建了一个宏大的宇宙观，黑暗森林法则令人震撼。这不仅是一部科幻小说，更是对人性、文明和宇宙的深刻思考。从文革时期的叶文洁，到面壁者罗辑，再到执剑人程心，每个人物都承载着人类文明的命运。作者用硬科幻的方式，探讨了文明的本质和生存的意义。读完这本书，会让人重新审视人类在宇宙中的位置。',
      status: 'pending',
      createTime: '2024-01-18 09:15:00',
      likes: 445,
      comments: 123,
      helpful: 367,
    },
    {
      id: 4,
      bookName: '平凡的世界',
      bookCover: 'https://images.unsplash.com/photo-1524995997946-a1c2e315a42f?w=100',
      userName: '赵六',
      rating: 3,
      title: '平凡中的伟大',
      content: '路遥的《平凡的世界》描绘了改革开放初期陕北农村的生活画卷...',
      fullContent: '路遥的《平凡的世界》描绘了改革开放初期陕北农村的生活画卷。孙少平、孙少安兄弟的奋斗历程，展现了那个时代普通人的命运和选择。虽然故事背景是上世纪七八十年代，但书中传递的精神力量至今仍然激励着人们。不过，书中部分情节略显冗长，节奏稍慢。',
      status: 'rejected',
      rejectReason: '评价过于简短，缺乏深度分析和个人见解',
      createTime: '2024-01-17 14:45:00',
      likes: 67,
      comments: 18,
      helpful: 42,
    },
    {
      id: 5,
      bookName: '1984',
      bookCover: 'https://images.unsplash.com/photo-1495446815901-a7297e633e8d?w=100',
      userName: '钱七',
      rating: 5,
      title: '反乌托邦的经典之作',
      content: '乔治·奥威尔的《1984》是一部预言式的小说，书中描绘的极权社会令人不寒而栗...',
      fullContent: '乔治·奥威尔的《1984》是一部预言式的小说，书中描绘的极权社会令人不寒而栗。"老大哥在看着你"、"战争即和平"、"自由即奴役"等概念，揭示了极权统治下人性的扭曲。温斯顿的反抗与最终的屈服，展现了个体在强权面前的无力。这本书写于1949年，但其警示意义至今不减。每个人都应该读一读这本书，思考自由和真理的价值。',
      status: 'approved',
      createTime: '2024-01-16 11:20:00',
      likes: 334,
      comments: 89,
      helpful: 278,
    },
  ])

  // 状态标签配置
  const statusConfig = {
    pending: { text: '待审核', color: 'orange' },
    approved: { text: '已通过', color: 'green' },
    rejected: { text: '已拒绝', color: 'red' },
  }

  // 查看详情
  const handleViewDetail = (record) => {
    setCurrentReview(record)
    setDetailVisible(true)
  }

  // 通过审核
  const handleApprove = async (record) => {
    Modal.confirm({
      title: '确认通过',
      content: `确定通过用户"${record.userName}"的书评吗？`,
      onOk: async () => {
        try {
          await dispatch(reviewBookReview({ 
            id: record.id, 
            data: { status: 'approved' } 
          })).unwrap()
          message.success('审核通过')
          // 重新加载列表
          dispatch(fetchPendingReviews({ page, size: pageSize }))
        } catch (error) {
          message.error(error?.message || '审核失败')
        }
      },
    })
  }

  // 拒绝审核
  const handleReject = (record) => {
    setCurrentReview(record)
    setRejectVisible(true)
  }

  // 确认拒绝
  const confirmReject = async () => {
    if (!rejectReason.trim()) {
      message.warning('请输入拒绝原因')
      return
    }
    
    try {
      if (currentReview?.isBatch) {
        // 批量拒绝
        await Promise.all(
          selectedRowKeys.map(id =>
            dispatch(reviewBookReview({ 
              id, 
              data: { status: 'rejected', reason: rejectReason } 
            })).unwrap()
          )
        )
        setSelectedRowKeys([])
        message.success(`已拒绝 ${selectedRowKeys.length} 条书评`)
      } else {
        // 单个拒绝
        await dispatch(reviewBookReview({ 
          id: currentReview.id, 
          data: { status: 'rejected', reason: rejectReason } 
        })).unwrap()
        message.success('已拒绝该书评')
      }
      
      // 重新加载列表
      dispatch(fetchPendingReviews({ page, size: pageSize }))
    } catch (error) {
      message.error(error?.message || '操作失败')
    }
    
    setRejectVisible(false)
    setRejectReason('')
  }

  // 批量通过
  const handleBatchApprove = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要审核的书评')
      return
    }
    Modal.confirm({
      title: '批量通过',
      content: `确定通过选中的 ${selectedRowKeys.length} 条书评吗？`,
      onOk: async () => {
        try {
          await Promise.all(
            selectedRowKeys.map(id =>
              dispatch(reviewBookReview({ 
                id, 
                data: { status: 'approved' } 
              })).unwrap()
            )
          )
          setSelectedRowKeys([])
          message.success('批量审核通过')
          // 重新加载列表
          dispatch(fetchPendingReviews({ page, size: pageSize }))
        } catch (error) {
          message.error(error?.message || '批量审核失败')
        }
      },
    })
  }

  // 批量拒绝
  const handleBatchReject = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要拒绝的书评')
      return
    }
    setRejectVisible(true)
    setCurrentReview({ isBatch: true })
  }

  // 导出数据
  const handleExport = () => {
    message.success('开始导出数据')
  }

  // 使用后端数据或模拟数据
  const actualDataSource = reviewList.length > 0 ? reviewList : dataSource

  // 根据Tab筛选数据
  const filteredData = actualDataSource.filter(item => {
    if (activeTab === 'all') return true
    return item.status === activeTab
  })

  // 统计各状态数量
  const getStatusCount = (status) => {
    if (status === 'all') return actualDataSource.length
    return actualDataSource.filter(item => item.status === status).length
  }

  // 处理分页变化
  const handleTableChange = (pagination) => {
    setPage(pagination.current)
    setPageSize(pagination.pageSize)
  }

  const columns = [
    {
      title: '图书',
      dataIndex: 'bookName',
      key: 'bookName',
      width: 200,
      render: (text, record) => (
        <div className="book-info">
          <Image
            src={record.bookCover}
            alt={text}
            width={50}
            height={70}
            style={{ objectFit: 'cover', borderRadius: 4 }}
          />
          <span className="book-name">{text}</span>
        </div>
      ),
    },
    {
      title: '用户',
      dataIndex: 'userName',
      key: 'userName',
      width: 100,
    },
    {
      title: '评分',
      dataIndex: 'rating',
      key: 'rating',
      width: 150,
      render: (rating) => <Rate disabled value={rating} style={{ fontSize: 14 }} />,
    },
    {
      title: '书评标题',
      dataIndex: 'title',
      key: 'title',
      width: 200,
      ellipsis: true,
      render: (text) => (
        <Tooltip title={text}>
          <div className="review-title">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '书评内容',
      dataIndex: 'content',
      key: 'content',
      ellipsis: true,
      render: (text) => (
        <Tooltip title={text}>
          <div className="review-content">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => (
        <Tag color={statusConfig[status].color}>
          {statusConfig[status].text}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 160,
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button
              type="link"
              size="small"
              icon={<EyeOutlined />}
              onClick={() => handleViewDetail(record)}
            >
              详情
            </Button>
          </Tooltip>
          {record.status === 'pending' && (
            <>
              <Tooltip title="通过">
                <Button
                  type="link"
                  size="small"
                  icon={<CheckOutlined />}
                  style={{ color: '#52c41a' }}
                  onClick={() => handleApprove(record)}
                >
                  通过
                </Button>
              </Tooltip>
              <Button
                type="link"
                size="small"
                icon={<CloseOutlined />}
                danger
                onClick={() => handleReject(record)}
              >
                拒绝
              </Button>
            </>
          )}
        </Space>
      ),
    },
  ]

  const rowSelection = {
    selectedRowKeys,
    onChange: setSelectedRowKeys,
  }

  return (
    <div className="review-management-container">
      <Card className="table-card">
        <div className="tabs-header">
          <Tabs
            activeKey={activeTab}
            onChange={setActiveTab}
            className="status-tabs"
            items={[
              {
                key: 'all',
                label: `全部 (${getStatusCount('all')})`,
              },
              {
                key: 'pending',
                label: `待审核 (${getStatusCount('pending')})`,
              },
              {
                key: 'approved',
                label: `已通过 (${getStatusCount('approved')})`,
              },
              {
                key: 'rejected',
                label: `已拒绝 (${getStatusCount('rejected')})`,
              },
            ]}
          />
          <div className="tabs-actions">
            <Space>
              <Button
                type="primary"
                icon={<CheckOutlined />}
                onClick={handleBatchApprove}
                disabled={selectedRowKeys.length === 0 || activeTab !== 'pending'}
              >
                批量通过
              </Button>
              <Button
                danger
                icon={<CloseOutlined />}
                onClick={handleBatchReject}
                disabled={selectedRowKeys.length === 0 || activeTab !== 'pending'}
              >
                批量拒绝
              </Button>
              <Button icon={<DownloadOutlined />} onClick={handleExport}>
                导出数据
              </Button>
            </Space>
          </div>
        </div>

        {selectedRowKeys.length > 0 && (
          <div className="selection-bar">
            <span className="selection-info">
              已选择 {selectedRowKeys.length} 项
            </span>
          </div>
        )}

        <Table
          rowSelection={{
            ...rowSelection,
            getCheckboxProps: (record) => ({
              disabled: record.status !== 'pending',
            }),
          }}
          columns={columns}
          dataSource={filteredData}
          rowKey="id"
          loading={loading}
          scroll={{ x: 1400 }}
          pagination={{
            current: page,
            pageSize: pageSize,
            total: filteredData.length,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            pageSizeOptions: ['10', '20', '50', '100']
          }}
          onChange={handleTableChange}
        />
      </Card>

      {/* 详情弹窗 */}
      <Modal
        title="书评详情"
        open={detailVisible}
        onCancel={() => setDetailVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailVisible(false)}>
            关闭
          </Button>,
          currentReview?.status === 'pending' && (
            <Button
              key="approve"
              type="primary"
              icon={<CheckOutlined />}
              onClick={() => {
                handleApprove(currentReview)
                setDetailVisible(false)
              }}
            >
              通过
            </Button>
          ),
          currentReview?.status === 'pending' && (
            <Button
              key="reject"
              danger
              icon={<CloseOutlined />}
              onClick={() => {
                setDetailVisible(false)
                handleReject(currentReview)
              }}
            >
              拒绝
            </Button>
          ),
        ]}
        width={800}
      >
        {currentReview && (
          <div className="review-detail">
            <div className="detail-item">
              <label>图书信息：</label>
              <div className="book-detail">
                <Image
                  src={currentReview.bookCover}
                  alt={currentReview.bookName}
                  width={80}
                  height={110}
                />
                <span>{currentReview.bookName}</span>
              </div>
            </div>
            <div className="detail-item">
              <label>用户：</label>
              <span>{currentReview.userName}</span>
            </div>
            <div className="detail-item">
              <label>评分：</label>
              <Rate disabled value={currentReview.rating} />
              <span style={{ marginLeft: 8, color: '#faad14' }}>
                {currentReview.rating}.0
              </span>
            </div>
            <div className="detail-item">
              <label>书评标题：</label>
              <div className="review-title-full">{currentReview.title}</div>
            </div>
            <div className="detail-item">
              <label>书评内容：</label>
              <div className="review-full-content">{currentReview.fullContent}</div>
            </div>
            <div className="detail-item">
              <label>互动数据：</label>
              <Space size="large">
                <span>👍 点赞 {currentReview.likes}</span>
                <span>💬 评论 {currentReview.comments}</span>
                <span>✓ 有帮助 {currentReview.helpful}</span>
              </Space>
            </div>
            <div className="detail-item">
              <label>状态：</label>
              <Tag color={statusConfig[currentReview.status].color}>
                {statusConfig[currentReview.status].text}
              </Tag>
            </div>
            {currentReview.rejectReason && (
              <div className="detail-item">
                <label>拒绝原因：</label>
                <div className="reject-reason">{currentReview.rejectReason}</div>
              </div>
            )}
            <div className="detail-item">
              <label>创建时间：</label>
              <span>{currentReview.createTime}</span>
            </div>
          </div>
        )}
      </Modal>

      {/* 拒绝原因弹窗 */}
      <Modal
        title="拒绝书评"
        open={rejectVisible}
        onOk={confirmReject}
        onCancel={() => {
          setRejectVisible(false)
          setRejectReason('')
        }}
        okText="确定"
        cancelText="取消"
      >
        <div style={{ marginBottom: 16 }}>
          <p>请输入拒绝原因：</p>
          <TextArea
            rows={4}
            value={rejectReason}
            onChange={(e) => setRejectReason(e.target.value)}
            placeholder="请详细说明拒绝的原因，以便用户改进..."
            maxLength={200}
            showCount
          />
        </div>
      </Modal>
    </div>
  )
}

export default ReviewManagement
